Import csv into mysql using Python

by: grantpasley, 9 years ago


i have the following code to import a csv into mysql, if i want to create the column names from the first row of the csv rather than create columns manually what would i need to change to automate the column creation process?


import csv
import MySQLdb

mydb = MySQLdb.connect(host='localhost',
    user='lineimp',
    passwd='',
    db='mydb')
cursor = mydb.cursor()

csv_data = csv.reader(file('lines.csv'))
for row in csv_data:

    cursor.execute('INSERT INTO lines(USER_PRODUCT_ID, USER_NAME, PROD_NAME, AMOUNT  )' 'VALUES("%s", "%s", "%s")',
          row)

mydb.commit()
cursor.close()
print "Done"




You must be logged in to post. Please login or register an account.